<?php


namespace app\controller\api;


use app\BaseController;
use app\common\OrderStatus;
use app\services\order\OrderService;
use app\services\utils\RedisService;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class PaintController extends BaseController
{
    /**
     * 订单列表
     * @return \think\response\Json
     */
    public function getOrderList()
    {
        try {
            $where = [];
            $type = $this->request->param('type', 0);
            $search = $this->request->param('search', '', 'trim');
            if ($search) {
                if (isPhoneNumber($search)) {
                    $userId = Db::name('user')->where('mobile', $search)->value('id');
                } else {
                    $userId = Db::name('user')->where('invite_code', $search)->value('id');
                }
                $where[] = ['user_id|buy_user_id', '=', $userId];
            }
            $where[] = ['is_del', '=', 0];
            $where[] = ['is_pick', '=', 0];
            $paintId = $this->request->paintId;
            $where[] = ['paint_id', '=', $paintId];
            $where[] = ['update_time', '>=', date('Y-m-d 00:00:00')];
            $page = $this->page;
            $limit = $this->limit;
            if ($type == 0) {
                // 全部
                $where[] = ['split_order_sn', '=', '0'];
            } elseif ($type == 1) {
                // 待付款
                $where[] = ['order_status', '=', 1];
            } elseif ($type == 2) {
                // 待收款
                $where[] = ['order_status', '=', 2];
            } elseif ($type == 3) {
                // 待上架
                $where[] = ['order_status', '=', 4];
            } elseif ($type == 4) {
                // 已出
                $where[] = ['order_status', '=', 3];
            }
            $list = Db::name('order')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            if ($list['total']) {
                $goodsIdArr = array_column($list['data'], 'goods_id');
                $goodsList = Db::name('goods')->whereIn('id', $goodsIdArr)->column('goods_no,name,image', 'id');
                $userIdArr1 = array_column($list['data'], 'user_id');
                $userIdArr2 = array_column($list['data'], 'buy_user_id');
                $userIdArr3 = array_column($list['data'], 'sell_user_id');
                $userIdArr = array_unique(array_merge($userIdArr1, $userIdArr2, $userIdArr3));
                $userList = Db::name('user')->whereIn('id', $userIdArr)->column('user_name,mobile,invite_code', 'id');
                foreach ($list['data'] as &$v) {
                    $goodsId = $v['goods_id'];
                    $v['goods_no'] = $goodsList[$goodsId]['goods_no'] ?? '';
                    $v['goods_name'] = $goodsList[$goodsId]['name'] ?? "";
                    $v['goods_image'] = $goodsList[$goodsId]['image'] ?? "";
                    if (!in_array($v['order_status'], [4, 5, 6])) {
                        $sellUserId = $v['user_id'];
                        $buyUserId = $v['buy_user_id'];
                    } else {
                        $sellUserId = $v['sell_user_id'];
                        $buyUserId = $v['user_id'];
                    }
                    $v['sell_user_name'] = $userList[$sellUserId]['user_name'] ?? '';
                    $v['sell_user_mobile'] = $userList[$sellUserId]['mobile'] ?? '';
                    $v['sell_user_code'] = $userList[$sellUserId]['invite_code'] ?? '';
                    $v['buy_user_name'] = $userList[$buyUserId]['user_name'] ?? '';
                    $v['buy_user_mobile'] = $userList[$buyUserId]['mobile'] ?? '';
                    $v['buy_user_code'] = $userList[$buyUserId]['invite_code'] ?? '';
                }
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 我已收款
     */
    public function myReceipt()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $service = new OrderService();
            $service->confirmOrder($orderSn);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 我已付款
     * @return \think\response\Json
     */
    public function myHasPay()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $service = new OrderService();
            $service->hasPayOrder($orderSn);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 重选买家
     * @return \think\response\Json
     */
    public function choice()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $code = $this->request->param('code', '', 'trim');
            $userInfo = Db::name('user')->where('invite_code', $code)->find();
            if (!$userInfo) {
                throw new \Exception('指派人不存在');
            }
            Db::name('order')->where('order_sn', $orderSn)->update([
                'buy_user_id' => $userInfo['id'],
                'update_time' => date('Y-m-d H:i:s'),
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 一键收款
     * @return \think\response\Json
     */
    public function moreReceipt()
    {
        $key = "receipt:order:bench";
        Db::startTrans();
        try {
            if (Cache::get($key)) {
                throw new \Exception("请勿重复操作");
            }
            Cache::set($key, time(), 30);
            $paintId = $this->request->paintId;
            $orderList = Db::name('order')->where('paint_id', $paintId)
                ->where('order_status', 2)
                ->select();
            $service = new OrderService();
            foreach ($orderList as $orderInfo) {
                $orderSn = $orderInfo['order_sn'];
                $service->confirmOrder($orderSn);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 确认上架
     * @return \think\response\Json
     */
    public function confirmOnline()
    {
        Db::startTrans();
        try {
            $orderSnArr = $this->request->param('order_sn');
            foreach ($orderSnArr as $orderSn) {
                $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
                if (!$orderInfo) {
                    throw new \Exception("订单号错误");
                }
                if ($orderInfo['order_status'] != OrderStatus::WAIT_ONLINE) {
                    throw new \Exception("订单状态错误");
                }
                Db::name('order')->where('order_sn', $orderSn)->update([
                    'order_status' => OrderStatus::OVER,
                    'online_time' => time(),
                    'update_time' => getFormatDate()
                ]);
                // 更新盲盒的归属
                Db::name('goods')->where('id', $orderInfo['goods_id'])->update([
                    'is_appoint' => 0,
                    'update_time' => time(),
                ]);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 批量上架
     * @return \think\response\Json
     */
    public function batchOnline()
    {
        Db::startTrans();
        try {
            $paintId = $this->request->paintId;
            $orderList = Db::name('order')
                ->where('paint_id', $paintId)
                ->where('order_status', 4)
                ->select();
            foreach ($orderList as $orderInfo) {
                $orderSn = $orderInfo['order_sn'];
                Db::name('order')->where('order_sn', $orderSn)->update([
                    'order_status' => OrderStatus::OVER,
                    'online_time' => time(),
                    'update_time' => getFormatDate()
                ]);
                // 更新盲盒的归属
                Db::name('goods')->where('id', $orderInfo['goods_id'])->update([
                    'is_appoint' => 0,
                    'update_time' => time(),
                ]);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 提现列表
     * @return \think\response\Json
     */
    public function getWithdrawList()
    {
        try {
            $paintId = $this->request->paintId;
            $where [] = ['paint_id', '=', $paintId];
            $type = $this->request->param('type', 0);
            if ($type == 0) {
                $where [] = ['status', '=', 0];
            } else {
                $where [] = ['status', 'in', [1, 2]];
            }
            $list = Db::name('withdraw')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 提现审核
     * @return \think\response\Json
     */
    public function audit()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status'); //0待转账 1已打款 2打款失败
            $info = Db::name('withdraw')->where('id', $id)->find();
            if (!$info) {
                throw new \Exception("提现记录不存在");
            }
            if ($info['status'] != 0) {
                throw new \Exception("提现已审核");
            }
            $userInfo = Db::name('user')->where('id', $info['user_id'])->find();
            if (!$info) {
                throw new \Exception("提现用户不存在");
            }
            Db::name('withdraw')->where('id', $id)->update([
                'status' => $status,
                'confirm_date' => date('Y-m-d H:i:s')
            ]);
            if ($status == 2) {
                Db::name('user')->where('id', $info['user_id'])->inc("money", $info['money'])->update();
                Db::name('user')->where('id', $info['user_id'])->dec("withdraw", $info['money'])->update();
                Db::name('detailed_money')->insert([
                    'user_id' => $info['user_id'],
                    'user_name' => $userInfo['user_name'],
                    'user_mobile' => $userInfo['mobile'],
                    'money' => $info['money'],
                    'balance' => $userInfo['money'],
                    'relevant_user_id' => 0,
                    'relevant_name' => 0,
                    'type' => 2,
                    'order_sn' => $info['order_sn'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'remark' => '提现失败退款'
                ]);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 店业绩
     * @return \think\response\Json
     */
    public function statistics()
    {
        Db::startTrans();
        try {
            $where = [];
            $paintId = $this->request->param('paint_id');
            $where[] = ['paint_id', '=', $paintId];
            $where[] = ['is_split', '=', 0];
            $time = $this->request->param('time');
            $where[] = ['create_time', 'between', [$time . ' 00:00:00', $time . ' 23:59:59']];

            $list = Db::name('order')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            if ($list['total']) {
                $goodsIdArr = array_column($list['data'], 'goods_id');
                $goodsList = Db::name('goods')->whereIn('id', $goodsIdArr)->column('goods_no,name,image', 'id');
                $userIdArr1 = array_column($list['data'], 'user_id');
                $userIdArr2 = array_column($list['data'], 'buy_user_id');
                $userIdArr3 = array_column($list['data'], 'sell_user_id');
                $userIdArr = array_unique(array_merge($userIdArr1, $userIdArr2, $userIdArr3));
                $userList = Db::name('user')->whereIn('id', $userIdArr)->column('user_name,mobile,invite_code', 'id');
                foreach ($list['data'] as &$v) {
                    $goodsId = $v['goods_id'];
                    $v['goods_no'] = $goodsList[$goodsId]['goods_no'] ?? '';
                    $v['goods_name'] = $goodsList[$goodsId]['name'] ?? "";
                    $v['goods_image'] = $goodsList[$goodsId]['image'] ?? "";
                    $sellUserId = $v['user_id'];
                    $buyUserId = $v['buy_user_id'];
                    $v['sell_user_name'] = $userList[$sellUserId]['user_name'] ?? '';
                    $v['sell_user_mobile'] = $userList[$sellUserId]['mobile'] ?? '';
                    $v['sell_user_code'] = $userList[$sellUserId]['invite_code'] ?? '';
                    $v['buy_user_name'] = $userList[$buyUserId]['user_name'] ?? '';
                    $v['buy_user_mobile'] = $userList[$buyUserId]['mobile'] ?? '';
                    $v['buy_user_code'] = $userList[$buyUserId]['invite_code'] ?? '';
                }
            }

            $totalAmount = Db::name('order')
                ->where($where)
                ->sum('price');
            $onlineFee = Db::name('order')
                ->where($where)
                ->sum('online_price');
            Db::commit();
            return $this->success(['list' => $list, 'total' => $list['total'], 'total_amount' => $totalAmount, 'online_fee' => $onlineFee]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 记账统计下载
     */
    public function exportStatisticsOrder()
    {
        try {
            $header = [
                'goods_name' => '藏品名称',
                'paint_name' => '藏馆',
                'sell_user_name' => '出售人',
                'sell_user_mobile' => '出售人手机号',
                'buy_user_name' => '购买人',
                'buy_user_mobile' => '购买人手机号',
                'price' => '订单金额',
                'online_price' => '上架费',
                'order_status_text' => '状态',
                'create_time' => '抢单时间',
            ];
            $where = [];
            $paintId = $this->request->param('paint_id');
            $paintInfo = Db::name('paint')->where('id', $paintId)->find();
            $where[] = ['paint_id', '=', $paintId];
            $where[] = ['is_split', '=', 0];
            $time = $this->request->param('time');
            $where[] = ['create_time', 'between', [$time . ' 00:00:00', $time . ' 23:59:59']];
            $list = Db::name('order')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            if ($list['total']) {
                $goodsIdArr = array_column($list['data'], 'goods_id');
                $goodsList = Db::name('goods')->whereIn('id', $goodsIdArr)->column('goods_no,name,image', 'id');
                $userIdArr1 = array_column($list['data'], 'user_id');
                $userIdArr2 = array_column($list['data'], 'buy_user_id');
                $userIdArr3 = array_column($list['data'], 'sell_user_id');
                $userIdArr = array_unique(array_merge($userIdArr1, $userIdArr2, $userIdArr3));
                $userList = Db::name('user')->whereIn('id', $userIdArr)->column('user_name,mobile,invite_code', 'id');
                foreach ($list['data'] as &$v) {
                    $goodsId = $v['goods_id'];
                    $v['goods_no'] = $goodsList[$goodsId]['goods_no'] ?? '';
                    $v['goods_name'] = $goodsList[$goodsId]['name'] ?? "";
                    $v['goods_image'] = $goodsList[$goodsId]['image'] ?? "";
                    $sellUserId = $v['user_id'];
                    $buyUserId = $v['buy_user_id'];
                    $v['sell_user_name'] = $userList[$sellUserId]['user_name'] ?? '';
                    $v['sell_user_mobile'] = $userList[$sellUserId]['mobile'] ?? '';
                    $v['sell_user_code'] = $userList[$sellUserId]['invite_code'] ?? '';
                    $v['buy_user_name'] = $userList[$buyUserId]['user_name'] ?? '';
                    $v['buy_user_mobile'] = $userList[$buyUserId]['mobile'] ?? '';
                    $v['buy_user_code'] = $userList[$buyUserId]['invite_code'] ?? '';
                    $v['paint_name'] = Db::name('paint')->where('id', $v['paint_id'])->value('paint_name');
                    $v['order_status_text'] = OrderStatus::getOrderStatusTxt($v['order_status']);
                }
            }
            $totalAmount = Db::name('order')
                ->where($where)
                ->sum('price');
            $totalAmount1 = Db::name('order')
                ->where('paint_id', $paintId)
                ->where('is_split', 0)
                ->sum('price');
            $onlineFee = Db::name('order')
                ->where($where)
                ->sum('online_price');
            $onlineFee1 = Db::name('order')
                ->where('paint_id', $paintId)
                ->where('is_split', 0)
                ->sum('online_price');
            $filePath = exportExcel($header, $list['data'], '', $totalAmount, $totalAmount1, $onlineFee, $onlineFee1, $time,$paintInfo);
            return $this->success(['file_path' => $filePath]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取阁主列表
     * @return \think\response\Json
     */
    public function getPaintList()
    {
        try {
            $userId = $this->request->userId;
            $list = Db::name('paint')->where('relation', 'like', '%' . $userId . '%')->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取商品转场列表
     * @return \think\response\Json
     */
    public function getGoodsTransList()
    {
        try {
            $paintId = $this->request->paintId;
            $type = $this->request->param('type', 0);
            $where = [];
            if ($type == 0) {
                $where[] = ['trans_paint_id', '=', $paintId];
                $where[] = ['status', '=', 0];
            } elseif ($type == 1) {
                $where[] = ['trans_paint_id', '=', $paintId];
                $where[] = ['status', 'in', [1, 2]];
            } else {
                $where[] = ['paint_id', '=', $paintId];
                $where[] = ['status', 'in', [1, 2]];
            }
            $list = Db::name('goods_trans')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $goodsInfo = Db::name('goods')->where('id', $v['goods_id'])->find();
                $v['goods_no'] = $goodsInfo['goods_no'];
                $v['goods_name'] = $goodsInfo['name'];
                $v['goods_category'] = $goodsInfo['category'];
                $userInfo = Db::name('user')->where('id', $v['user_id'])->find();
                $v['sell_user_name'] = $userInfo['user_name'];
                $v['sell_user_mobile'] = $userInfo['mobile'];
                $v['old_paint_name'] = Db::name('paint')->where('id', $v['paint_id'])->value('paint_name');
                $v['new_paint_name'] = Db::name('paint')->where('id', $v['trans_paint_id'])->value('paint_name');
                $v['create_time'] = date('Y-m-d\TH:i:s', $v['create_time']);
                $v['update_time'] = date('Y-m-d\TH:i:s', $v['update_time']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 转场审核
     * @return \think\response\Json
     */
    public function transAudit()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status'); //2同意 3拒绝
            if (!in_array($status, [2, 3])) {
                throw new \Exception("审核状态错误");
            }
            $info = Db::name('goods_trans')->where('id', $id)->find();
            if (!$info) {
                throw new \Exception("转场记录不存在");
            }
            if ($info['status'] != 0) {
                throw new \Exception("转场状态错误");
            }
            Db::name('goods_trans')->where('id', $id)->update(['status' => $status, 'update_time' => time()]);
            if ($status == 2) {
                Db::name('goods')->where('id', $info['goods_id'])->update([
                    'paint_id' => $info['trans_paint_id'],
                    'trans_time' => date('Y-m-d H:i:s'),
                    'trans_status' => 2,
                    'update_time' => time()
                ]);
                Db::name('order')->where('order_sn', $info['order_sn'])->update([
                    'paint_id' => $info['trans_paint_id'],
                    'update_time' => date('Y-m-d H:i:s'),
                ]);
            } else {
                Db::name('goods')->where('id', $info['goods_id'])->update([
                    'trans_time' => date('Y-m-d H:i:s'),
                    'trans_status' => 3,
                    'update_time' => time()
                ]);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 兑换列表
     * @return \think\response\Json
     */
    public function getExchangeList()
    {
        try {
            $type = $this->request->param('type', 0, 'int');
            $where = [];
            $where[] = ['paint_id', '=', $this->request->paintId];
            if ($type) {
                $where[] = ['order_status', '=', $type];
            }
            $page = $this->page;
            $limit = $this->limit;
            $list = Db::name('exchange_order')
                ->where($where)
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d\TH:i:s', $v['create_time']);
                $v['update_time'] = date('Y-m-d\TH:i:s', $v['update_time']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 提货列表
     * @return \think\response\Json
     */
    public function getPickList()
    {
        try {
            $type = $this->request->param('type', 0, 'int');
            $where = [];
            $where[] = ['paint_id', '=', $this->request->paintId];
            if ($type) {
                $where[] = ['order_status', '=', $type];
            }
            $page = $this->page;
            $limit = $this->limit;
            $list = Db::name('order_pick')
                ->where($where)
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d\TH:i:s', $v['create_time']);
                $v['update_time'] = date('Y-m-d\TH:i:s', $v['update_time']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 设置店铺编号
     * @return \think\response\Json
     */
    public function setShop()
    {
        try {
            $code = $this->request->param('code', 0, 'int');
            if (strlen($code) != 6) {
                throw new \Exception('请设置六位数编号');
            }
            $paintId = $this->request->param('paint_id');
            $paintInfo = Db::name('paint')->where('id', $paintId)->find();
            if (!$paintInfo) {
                throw new \Exception('店铺不存在');
            }
            Db::name('paint')->where('id', $paintId)->update([
                'paint_code' => $paintInfo['paint_prefix'] . $code
            ]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}